package com.godenwater.web.listener;

import com.godenwater.recv.decode.YlnMessageDecoder;
import com.godenwater.recv.model.CommonMessage;
import com.godenwater.recv.server.all.RtuConfig;
import com.godenwater.recv.service.MessageYlnConsumer;
import com.godenwater.utils.ByteUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MsgYlnFileListener implements FileAlterationListener {

	MsgFileMonitor monitor = null;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

	@Override
	public void onStart(FileAlterationObserver observer) {
		// System.out.println("onStart");
	}

	@Override
	public void onDirectoryCreate(File directory) {
		System.out.println("onDirectoryCreate:" + directory.getName());
	}

	@Override
	public void onDirectoryChange(File directory) {
		System.out.println("onDirectoryChange:" + directory.getName());
	}

	@Override
	public void onDirectoryDelete(File directory) {
		System.out.println("onDirectoryDelete:" + directory.getName());
	}

	@Override
	public void onFileCreate(File file) {
		System.out.println("YLN file create:" + file.getName());
		// FileUtils.copyFileToDirectory(srcFile, destDir);
		String fileName = file.getName();
		String[] fileInfo = fileName.split("_");

		String channel = fileInfo[0];
		String stcd = fileInfo[1];
		String crcflag = fileInfo[2];
		// 第一步：读取报文文件
		List<String> lines;
		try {
			// lines = Files.readAllLines(Paths.get("/tmp/test.csv"),
			// Charset.forName("UTF-8"));
			lines = FileUtils.readLines(file, "UTF-8");
			for (String line : lines) {
				System.out.println("READ YLN>> " + line);

				// 1.1：转换为报文字节数组
 				byte[] bytes = ByteUtils.hexStringToBytes(line);
//
//				// //1.2：解析报文
//				// 不能使用74做为中心站名
 				 CommonMessage message =  YlnMessageDecoder.decode(bytes);
 				MessageYlnConsumer consumer = new MessageYlnConsumer();
 				consumer.process(channel, message);
			}

			// 最后，将文件拷贝至成功目录
			String rcvpath = RtuConfig.getMsgRcvPath(); 
			FileUtils.copyFileToDirectory(file, new File(rcvpath + "/YLN/suc/" + sdf.format(new Date())),
					true);
			// 然后清除目录文件
			FileUtils.deleteQuietly(file);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onFileChange(File file) {
		System.out.println("onFileChange:" + file.getName());
	}

	@Override
	public void onFileDelete(File file) {
		System.out.println("onFileDelete:" + file.getName());
	}

	@Override
	public void onStop(FileAlterationObserver observer) {
		// System.out.println("onStop");
	}

}
